#include "selectwnddialog.h"
#include "urdfwidget.h"
#include "autoform.h"
#include "models/robot.h"
#include "ui_autoform.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPropertyAnimation>
#include <QScroller>
#include <QStandardItemModel>
#include <QStyledItemDelegate>
#include <mainwindow.h>
#include <models/robotlist.h>
#include <models/syssettingmodel.h>
#include "upperlimbwidget.h"
#include"globalcmdwidget.h"
#include "urdfwidget.h"
#include "audiocmdwidget.h"

AutoForm::AutoForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Auto_Form)
    ,m_pAddWndBtn(NULL)
    ,m_pStartBtn(NULL)
    ,m_pStopBtn(NULL)
{
    setAttribute(Qt::WA_StyledBackground, true);
    ui->setupUi(this);

    // 创建方向控制器
    m_directionCtrl = new DirectionControlWidget(ui->frame);
    // 创建转向控制器
    m_turnCtrl = new TurnController(ui->frame);

    // createUpperWidget();
    // createLowerWidget();
    connect(m_directionCtrl, &DirectionControlWidget::directionChanged,
            this, &AutoForm::onDirectionChanged);
    connect(m_turnCtrl, &TurnController::turnChanged,
            this, &AutoForm::onTurnChanged);
    m_directionCtrl->setVisible(SysSettingModel::getInstance()->bShowVirtualBtns());
    m_turnCtrl->setVisible(SysSettingModel::getInstance()->bShowVirtualBtns());
    connect(SysSettingModel::getInstance(),&SysSettingModel::showVirtualCtrlBtnChanged,this,[=]{
        m_directionCtrl->setVisible(SysSettingModel::getInstance()->bShowVirtualBtns());
        m_turnCtrl->setVisible(SysSettingModel::getInstance()->bShowVirtualBtns());
    });
    //如果摇杆设置发生变化
    connect(SysSettingModel::getInstance(),&SysSettingModel::showJoystickBtnChanged,this,[=]{
        Robot * pRobot = RobotList::getInstance()->getCurRobot();
        pRobot->setJoystickState(SysSettingModel::getInstance()->bShowJoystickBtns());
    });


    //m_pVoiceAnim = new VoiceAnimation(this);
    // // 将动画控件放在窗口中央
    // connect(VoiceRecognition::getInstance(), &VoiceRecognition::showRecIco, this, [&] (bool bIshow,QString strCmd) {
    //     m_pVoiceAnim->setText(strCmd);
    //     if(bIshow)
    //         m_pVoiceAnim->startAnimation();
    //     else
    //         m_pVoiceAnim->stopAnimation();
    // });
    // connect(m_pVoiceAnim, &VoiceAnimation::clicked, this, [&](){
    //     VoiceRecognition::getInstance()->setStatus(false);
    // });
    //创建一个添加按钮，用于添加小窗口
    m_pAddWndBtn = new TouchButton(this);
    m_pAddWndBtn->setStyleSheet("QPushButton { border-image:url(:/images/new_window.png); } QPushButton:pressed {  border-image:url(:/images/new_window_pressed.png); }");

    m_pAddWndBtn->setFixedSize(80*g_xScale,80 *g_xScale);
    connect(m_pAddWndBtn,&QPushButton::clicked, this, &AutoForm::onAddWndBtnClick);

    m_pStartBtn = new TouchButton(this);
    m_pStartBtn->setStyleSheet("QPushButton { border-image:url(:/images/start.png); }QPushButton:pressed{border-image:url(:/images/start_pressed.png);}");
    m_pStartBtn->setFixedSize(100*g_xScale,100 *g_xScale);
    connect(m_pStartBtn,&QPushButton::clicked, this, [](){
        Robot * pRobot = RobotList::getInstance()->getCurRobot();
        if(pRobot)
        {
            pRobot->setStartCmd();
        }
    });

    m_pStopBtn = new TouchButton(this);
    m_pStopBtn->setStyleSheet("QPushButton { border-image:url(:/images/stop.png); }QPushButton:pressed{border-image:url(:/images/stop_pressed.png);}");
    m_pStopBtn->setFixedSize(100*g_xScale,100 *g_xScale);
    connect(m_pStopBtn,&QPushButton::clicked, this, [](){
        Robot * pRobot = RobotList::getInstance()->getCurRobot();
        if(pRobot)
        {
            pRobot->setStopCmd();
        }
    });

    connect(RobotList::getInstance(), &RobotList::curRobotChanged, this, [&](Robot * pCurRobot, Robot * pLastRobot){
        clearWnd();
        if(pLastRobot)
        {
        }
        if(pCurRobot)
        {
            QList<int> lsWnd = pCurRobot->lsWnd();
            for(int i = 0; i < lsWnd.size(); ++i)
                addWnd(lsWnd[i]);
            if(lsWnd.size() == 0 && m_lsNoShowWnd.size() > 0)
                addWnd(m_lsNoShowWnd.begin().key());

            resetWndRect();
            connect(pCurRobot, &Robot::stageChanged,this,[=](){ui->label_stage->setText(QString("%1").arg(pCurRobot->getNStage()));});
            ui->label_stage->setText(QString("%1").arg(pCurRobot->getNStage()));
        }
    });


    scaleWidgets(this,g_xScale,g_yScale);
    connect(ui->pushButton_1,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=157;
        cur.nHexCmd=157;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });
    connect(ui->pushButton_2,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=158;
        cur.nHexCmd=158;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });
    connect(ui->pushButton_3,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=155;
        cur.nHexCmd=155;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });
    connect(ui->pushButton_4,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=156;
        cur.nHexCmd=156;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });
    connect(ui->pushButton_5,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=179;
        cur.nHexCmd=179;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });
    connect(ui->pushButton_6,&QPushButton::clicked,[=]{
        Command cur;
        cur.nID=153;
        cur.nHexCmd=153;
        Robot*pRobot=RobotList::getInstance()->getCurRobot();
        if(pRobot){
            pRobot->setUpperCmd(cur);
        }
    });

    ui->widget_specificUpper->setVisible(true);


}

AutoForm::~AutoForm()
{
    // for(auto it = m_vtVideo.begin(); it != m_vtVideo.end(); ++it)
    // {
    //     (*it)->stopVideo(true);
    //     delete (*it);
    // }
    // m_vtVideo.clear();
    delete ui;
}

void AutoForm::resizeEvent(QResizeEvent* event)
{

    updateDirectionControllerPosition();
    updateTurnControllerPosition();
    // m_pVoiceAnim->move((width() - m_pVoiceAnim->width()) / 2,
    //                    (height() - m_pVoiceAnim->height()) / 2);
    //初始化添加按钮位置
    resetWndRect();

    m_pStartBtn->move(100 * g_xScale,500*g_yScale);
    m_pStopBtn->move(width() - 200*g_xScale,500 *g_yScale);



    QWidget::resizeEvent(event);
}

void AutoForm::updateDirectionControllerPosition()
{
    if (!ui->direct_widget || !m_directionCtrl) return;

    // 获取direct_widget的位置和尺寸
    QRect directRect = ui->direct_widget->geometry();

    // 设置控制器的大小（取较小值的70%）
    int controlSize = qMin(directRect.width(), directRect.height())*0.8 ;

    // 计算居中位置（相对于direct_widget的位置）
    int x = directRect.x() + (directRect.width() - controlSize) / 2;
    int y = directRect.y() + (directRect.height() - controlSize) / 2;

    // 设置控制器的位置和大小
    m_directionCtrl->setGeometry(x, y, controlSize, controlSize);
}

void AutoForm::updateTurnControllerPosition()
{
    if (!ui->turn_widget || !m_turnCtrl) return;

    // 获取turn_widget的位置和尺寸
    QRect turnRect = ui->turn_widget->geometry();

    // 设置控制器的大小（取较小值的70%）
    int width = turnRect.width()*0.8;
    int height = turnRect.height()*0.8;

    // 计算居中位置
    int x = turnRect.x() + (turnRect.width() - width) / 2;
    int y = turnRect.y() + (turnRect.height() - height) / 2;

    // 设置控制器的位置和大小
    m_turnCtrl->setGeometry(x, y, width, height);
}

void AutoForm::clearWnd()
{
    for(int i = 0; i < m_lsWnd.size(); ++i)
    {
        m_lsWnd[i]->deleteLater();
    }
    m_lsWnd.clear();
    m_lsNoShowWnd.clear();
    Robot* pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot)
    {
        m_lsNoShowWnd.insert(1001,"URDF");
        if(pRobot->hasSlam())
        {
            m_lsNoShowWnd.insert(1002,"SLAM");
        }
        QList<VideoInfo> lsVideo = pRobot->lsVideo();
        for(int i = 0; i < lsVideo.size(); ++i)
        {
            m_lsNoShowWnd.insert(i+1,lsVideo[i].strName);
        }
    }
}

void AutoForm::addWnd(int nID)
{
    if(m_lsNoShowWnd.contains(nID))
    {
        Window * pWnd = NULL;
        switch(nID)
        {
        case 1001:
            pWnd = new Window(Window_Urdf,ui->frame,nID,m_lsNoShowWnd[nID]);
            break;
        case 1002:
        {
            Robot* pRobot = RobotList::getInstance()->getCurRobot();
            if(pRobot && pRobot->hasSlam())
                pWnd = new Window(Window_Slam,ui->frame,nID,m_lsNoShowWnd[nID]);
        }
        break;
        default:
            if(nID > 0)
            {
                int nIndex = nID - 1;
                Robot * pRobot = RobotList::getInstance()->getCurRobot();
                if(pRobot)
                {
                    QList<VideoInfo> lsVideo = pRobot->lsVideo();
                    if(lsVideo.size() > nIndex)
                        pWnd = new Window(Window_Video,ui->frame,nID,m_lsNoShowWnd[nID],lsVideo[nIndex].strUrl);
                }
            }
            break;
        }
        if(pWnd)
        {
            pWnd->show();
            m_lsWnd.push_back(pWnd);
            connect(pWnd,&Window::closeClicked,this,&AutoForm::removeWindow);
            connect(pWnd,&Window::windowClicked,this,&AutoForm::setWindowMax);
        }
        m_lsNoShowWnd.remove(nID);
        if(m_lsNoShowWnd.size() == 0)
        {
            m_pAddWndBtn->hide();
        }
        else
            m_pAddWndBtn->show();

    }
}

void AutoForm::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    updateDirectionControllerPosition();
    updateTurnControllerPosition();
    Robot * pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot && pRobot->hasPerception())
    {
        ui->audio_file_btn->show();
    }
    else
    {
        ui->audio_file_btn->hide();
    }
}

void AutoForm::onDirectionChanged(double x, double y)
{
    Robot * pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot)
    {
        pRobot->setMove(x,y);
    }
}

void AutoForm::onTurnChanged(double x)
{
    Robot * pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot)
    {
        pRobot->setTurn(x);
    }
}


void AutoForm::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        QPoint pos = event->pos();
        QRect directWidgetRect = ui->direct_widget->geometry();
        QRect turnWidgetRect = ui->turn_widget->geometry();

        // 检查点击是否在direct_widget内
        if (directWidgetRect.contains(pos)) {
            // 获取控制器的大小
            int controlSize = m_directionCtrl->width();

            // 计算新位置，使控制器中心在点击位置
            int x = pos.x() - controlSize / 2;
            int y = pos.y() - controlSize / 2;

            // 移动控制器
            m_directionCtrl->move(x, y);

            // 开始拖动
            m_directionCtrl->startDragging(pos);
        }
        // 检查点击是否在turn_widget内
        else if (turnWidgetRect.contains(pos)) {
            // 获取控制器的大小
            int width = m_turnCtrl->width();
            int height = m_turnCtrl->height();

            // 计算新位置，使控制器中心在点击位置
            int x = pos.x() - width / 2;
            int y = pos.y() - height / 2;

            // 移动控制器
            m_turnCtrl->move(x, y);

            // 开始拖动
            m_turnCtrl->startDragging(pos);
        }
    }
    QWidget::mousePressEvent(event);
}

void AutoForm::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        // 松开鼠标时恢复控制器到中心位置
        updateDirectionControllerPosition();
        updateTurnControllerPosition();
    }
    QWidget::mouseReleaseEvent(event);
}

void AutoForm::on_upper_limb_btn_clicked()
{
    if(ui->upper_limb_btn->isChecked())
    {
        UpperLimbWidget * pWidget = new UpperLimbWidget(0,this);
        connect(pWidget, &QWidget::destroyed, this, [=]() {
            ui->upper_limb_btn->setChecked(false);
        });
        QPoint pt = QPoint((ui->menu_widget->geometry().left()+ui->menu_widget->geometry().right()-pWidget->width())/2, ui->menu_widget->y() - pWidget->height());
        pWidget->move(mapToGlobal(pt));
        // 显示窗口
        pWidget->show();
    }
}

void AutoForm::on_global_cmd_btn_clicked()
{
    if(ui->global_cmd_btn->isChecked())
    {
        GlobalCmdWidget * pWidget = new GlobalCmdWidget(0,this);
        connect(pWidget, &QWidget::destroyed, this, [=]() {
            ui->global_cmd_btn->setChecked(false);
        });
        QPoint pt = QPoint((ui->menu_widget->geometry().left()+ui->menu_widget->geometry().right()-pWidget->width())/2, ui->menu_widget->y() - pWidget->height());
        pWidget->move(mapToGlobal(pt));
        // 显示窗口
        pWidget->show();
    }
}

void AutoForm::on_audio_file_btn_clicked()
{
    if(ui->audio_file_btn->isChecked())
    {
        AudioCmdWidget * pWidget = new AudioCmdWidget(this);
        connect(pWidget, &QWidget::destroyed, this, [=]() {
            ui->audio_file_btn->setChecked(false);
        });
        QPoint pt = QPoint((ui->menu_widget->geometry().left()+ui->menu_widget->geometry().right()-pWidget->width())/2, ui->menu_widget->y() - pWidget->height());
        pWidget->move(mapToGlobal(pt));
        // 显示窗口
        pWidget->show();
    }
}


void AutoForm::onAddWndBtnClick()
{
    //弹出窗口
    Robot* pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot)
    {
        SelectWndDialog  dlg(m_lsNoShowWnd,MainWindow::getInstance());
        int nID = dlg.exec();
        if(nID > 0)
        {
            addWnd(nID);
            resetWndRect();
        }
    }

}

void AutoForm::removeWindow(Window *pWnd)
{
    m_lsWnd.removeOne(pWnd);
    m_lsNoShowWnd.insert(pWnd->nID(),pWnd->strName());
    pWnd->deleteLater();
    resetWndRect();
    m_pAddWndBtn->show();
}

void AutoForm::setWindowMax(Window *pWnd)
{
    int nIndex = m_lsWnd.indexOf(pWnd);
    if(nIndex > 0)
    {
        m_lsWnd.swapItemsAt(nIndex,0);
        resetWndRect();
    }
}

void AutoForm::onShowTempratureWarn(QList<QString> lsStr)
{
    qDebug() << "got too high" << lsStr.size();

    // 清除 widget_temprature 的旧内容
    QLayout* oldLayout = ui->widget_temprature->layout();
    if (oldLayout) {
        QLayoutItem* item;
        while ((item = oldLayout->takeAt(0)) != nullptr) {
            delete item->widget();
            delete item;
        }
        delete oldLayout;
    }

    // 创建新的 QGridLayout（3列）
    QGridLayout* gridLayout = new QGridLayout(ui->widget_temprature);
    gridLayout->setSpacing(10); // 控件间距
    gridLayout->setContentsMargins(5, 5, 5, 5); // 边距

    int row = 0;
    int col = 0;

    for (const QString& str : lsStr) {
        // 创建一个小部件容器（用于放红灯和文本）
        QWidget* container = new QWidget(ui->widget_temprature);
        QHBoxLayout* hLayout = new QHBoxLayout(container);
        hLayout->setSpacing(5); // 红灯和文本间距
        hLayout->setContentsMargins(0, 0, 0, 0); // 无额外边距

        // 创建红灯（使用 QLabel + 红色圆形样式）
        QLabel* redLight = new QLabel(container);
        redLight->setFixedSize(12, 12); // 固定大小
        redLight->setStyleSheet(
            "background-color: red;"
            "border-radius: 6px;" // 圆形
            "border: 1px solid darkred;"
        );

        // 创建温度文本标签
        QLabel* textLabel = new QLabel(str, container);
        textLabel->setStyleSheet("color: white; font-weight: bold;font-size:20px;qproperty-wordWrap: true;");

        // 将红灯和文本添加到水平布局
        hLayout->addWidget(redLight);
        hLayout->addWidget(textLabel);

        // 将整个容器添加到栅格布局
        gridLayout->addWidget(container, row, col);

        // 更新行和列（3列布局）
        col++;
        if (col >= 4) {
            col = 0;
            row++;
        }
    }

    ui->widget_temprature->setLayout(gridLayout);
}

void AutoForm::scaleWidgets(QWidget *widget, double xScale, double yScale)
{
    Q_UNUSED(widget)
    Q_UNUSED(yScale)
    ui->direct_widget->setFixedSize(int(ui->direct_widget->width() * xScale),int(ui->direct_widget->height() * xScale));
    ui->turn_widget->setFixedSize(int(ui->turn_widget->width() * xScale),int(ui->turn_widget->height() * xScale));
    ui->audio_file_btn->setFixedSize(int(ui->audio_file_btn->width() * xScale),int(ui->audio_file_btn->height() * xScale));
    ui->global_cmd_btn->setFixedSize(int(ui->global_cmd_btn->width() * xScale),int(ui->global_cmd_btn->height() * xScale));
    QFont font = ui->global_cmd_btn->font();
    font.setPixelSize(int(font.pointSize()*xScale));
    ui->audio_file_btn->setFont(font);
    ui->global_cmd_btn->setFont(font);
    ui->upper_limb_btn->setFixedSize(int(ui->upper_limb_btn->width() * xScale),int(ui->upper_limb_btn->height() * xScale));
    ui->upper_limb_btn->setFont(font);
    ui->frame->setContentsMargins(0,0,int(80*xScale),0);
}


void AutoForm::resetWndRect()
{
    //保存最新的排序到数据库
    int nLeft = width();
    for(int i = 1; i < m_lsWnd.size(); ++i)
    {
        QSize sz = QSize(320*g_xScale,180*g_xScale);
        nLeft -= (sz.width()+1);
        m_lsWnd[i]->setGeometry(nLeft, 2, sz.width(),sz.height());
        m_lsWnd[i]->setBMax(false);
    }
    nLeft -= 100*g_xScale;
    m_pAddWndBtn->move(nLeft,50 * g_xScale);
    if(m_lsWnd.size() > 0)
    {
        //第一个窗口最大化,在最底层
        m_lsWnd[0]->setGeometry(0,0,width(),height());
        m_lsWnd[0]->setBMax(true);
        m_lsWnd[0]->lower();
    }
    Robot* pRobot = RobotList::getInstance()->getCurRobot();
    if(pRobot)
    {
        QList<int> ls;
        for(int i = 0; i < m_lsWnd.size(); ++i)
        {
            ls.push_back(m_lsWnd[i]->nID());
        }
        pRobot->setLsWnd(ls);
    }
}
